import Vue from "vue";
import Router from "vue-router";
import developerServe from "./modules/developerServe";
import user from "./modules/user";
import order from "./modules/order";
import shopping from "./modules/shopping";
import store from "@/store";
import { requestPool } from "../utils/request";

Vue.use(Router);

console.log();

export const asyncRouterMap = [user, shopping, order, developerServe];

export const asyncRouterMap2 = [user, shopping, order];

const router = new Router({
	mode: "hash",
	routes: [
		{
			path: "/login",
			name: "login",
			component: () =>
				import(/* webpackChunkName: "login" */ "@/pages/login/login"),
		},
		{
			path: "/",
			name: "frame",
			redirect: "/developer_serve",
			component: () => import("@/pages/frame/frame"),
			children: asyncRouterMap,
		},
		{
			path: "*",
			redirect: "/", //重定向
		},
	],
});

let hasTimeStamp = false;

router.beforeEach((to, from, next) => {
	if (!hasTimeStamp) {
		hasTimeStamp = true;
		next({
			replace: true,
			path: to,
		});
		return;
	}
	hasTimeStamp = false;
	requestPool.clear();
	var userData = localStorage.getItem("userData");
	if (userData) {
		if (!store.state.user.isLogin) {
			store.dispatch("restoreFromSession");
		}
		next();
	} else {
		if (to.path == "/home" || to.path == "/login") {
			next();
		} else {
			next({ name: "home" });
		}
	}
});

export default router;
